/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-17 10:59:16
 * @Description  : 物理文件相关接口
 */
const { Op } = require('sequelize')
const Mysequelize = require('@/models')
const R = require('@/models/Response')
const {
  Notice,
  NoticeUser,
  User,
  UserDepartment,
  Source
} = require('@/models/model')
const WpFile = require('@/models/fileModel')
const { ERROR_USER_CODE, ERROR_SOURCE_CODE } = require('@/constants/errorCode')
const { generatId } = require('@/utils/idUtil')
const { delModel, listModel, sortModel } = require('@/utils/controllerCommon')
const { convertFromBytes } = require('@/utils/format')
const {
  getFileInfo,
  writeFileInfo,
  createFileChunk,
  combine,
  addChunkToFileInfo
} = require('@/utils/upload')
const { dumpCheck } = require('@/utils/dumpCheck')
const fs = require('fs')
const { createFile } = require('@/middlewares/validateMiddlewares/fileValidate')

/**
 * 文件信息协商接口
 * @param {*} ctx
 * @returns
 */
module.exports.fileHandShark = async (ctx) => {
  // 完整文件md5和需要上传分片总的md5,到这里说明文件暂时不存在
  const { fileId, chunkIds, filename, size, parentId } = ctx.request.body
  // 说明这是第一次协商，文件分片一个都没有上传
  const resInfo = await writeFileInfo(
    fileId,
    filename,
    chunkIds,
    size,
    parentId
  )

  ctx.body = R.success({
    needs: resInfo.needs
  })
}

/**
 * 文件分片上传接口
 * @param {*} ctx
 * @returns
 */
module.exports.chunkUpload = async (ctx) => {
  // 到这里，说明该分片没有被上传
  // 完整文件md5和需要上传分片的md5
  const { fileId, chunkId } = ctx.request.body

  const fileBuffer = fs.readFileSync(ctx.request.files.file.filepath)

  // 处理分片
  await createFileChunk(chunkId, fileBuffer)
  // 添加分片信息到文件信息
  fileInfo = await addChunkToFileInfo(chunkId, fileId)
  // 还有需要的分片吗？
  if (fileInfo.needs.length > 0) {
    ctx.body = R.success({
      needs: fileInfo.needs
    })
  } else {
    // 全部传完了
    const t = await Mysequelize.transaction()
    try {
      await combine(fileInfo)
      await createFile(ctx, fileInfo, ctx.user.id, t)
      await t.commit()
      ctx.body = R.success({
        needs: []
      })
    } catch (e) {
      await t.rollback()
      console.log(e)
      ctx.body = R.error(ERROR_SOURCE_CODE.FILE_COMBINE_ERROR)
    }
  }
}
